package com.yzy.tomcat.state;

/**
 * @author yzy
 * Created by yzy on 2021-11-19
 */
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ThreadPoolExecutor;

import com.yzy.tomcat.TCPHandler;
import com.yzy.tomcat.servlet.DispatchServlet;
import com.yzy.tomcat.servlet.MyResponse;

public class WriteState implements HandlerState {

    private String request;
    public WriteState(String request) {
        this.request = request;
    }

    public WriteState() {
    }

    public void changeState(TCPHandler h) {
        // TODO Auto-generated method stub
        h.setState(new ReadState());
    }

    private DispatchServlet dispatchServlet = new DispatchServlet();

    public void handle(TCPHandler h, SelectionKey sk, SocketChannel sc,
                       ThreadPoolExecutor pool) throws IOException {

        MyResponse myResponse = new MyResponse(sc.socket().getOutputStream());

        String request = this.request;

        String resp = dispatchServlet.respone(myResponse, "success");

        ByteBuffer buf = ByteBuffer.wrap(resp.getBytes()); // wrap自動把buf的position設為0，所以不需要再flip()
        while (buf.hasRemaining()) {
            sc.write(buf); // 回傳給client回應字符串，發送buf的position位置 到limit位置為止之間的內容
        }

        h.setState(new ReadState()); // 改變狀態(SENDING->READING)
        sk.interestOps(SelectionKey.OP_READ); // 通過key改變通道註冊的事件
        sk.selector().wakeup(); // 使一個阻塞住的selector操作立即返回
    }
}
